<template>
    <view class="container">
        <form @submit="submitForm">
            <!-- 标题 -->
            <view class="title-section">
                <text class="title">随手拍上报</text>
            </view>

            <!-- 图片上传区域 -->
            <view class="form-item">
                <text class="label">拍摄照片</text>
                <view class="upload-area">
                    <view class="upload-btn" @click="chooseImage">
                        <image src="/static/add-image.png" mode="aspectFit"></image>
                        <text>点击拍照上传</text>
                    </view>
                    <view v-if="imageList.length > 0" class="image-preview">
                        <image 
                            v-for="(item, index) in imageList" 
                            :key="index" 
                            :src="item" 
                            mode="aspectFill"
                            @click="previewImage(index)"
                        ></image>
                    </view>
                </view>
            </view>

            <!-- 位置信息 -->
            <view class="form-item">
                <text class="label">当前位置</text>
                <view class="location-info" @click="getLocation">
                    <text>{{ locationInfo || '点击获取位置' }}</text>
                    <image src="/static/location.png" mode="aspectFit"></image>
                </view>
            </view>

            <!-- 描述信息 -->
            <view class="form-item">
                <text class="label">详细描述</text>
                <textarea 
                    v-model="description" 
                    placeholder="请描述您拍摄的内容..." 
                    maxlength="500"
                ></textarea>
            </view>

            <!-- 拍照时间 -->
            <view class="form-item">
                <text class="label">拍照时间</text>
                <text class="form-value">{{ createTime }}</text>
            </view>

            <!-- 所属社区 -->
            <view class="form-item">
                <text class="label">所属社区</text>
                <picker 
                    mode="selector" 
                    :range="communityList" 
                    :value="communityIndex" 
                    @change="onCommunityChange"
                >
                    <view class="picker">
                        {{ communityList[communityIndex] || '请选择社区' }}
                        <image src="/static/arrow-down.png" mode="aspectFit"></image>
                    </view>
                </picker>
            </view>

            <!-- 提交按钮 -->
            <view class="submit-section">
                <button form-type="submit" class="submit-btn">提交上报</button>
            </view>
        </form>
    </view>
</template>

<script>
import md5 from '@/libs/md5.js'; // 需要安装：npm install js-md5

export default {
    data() {
        return {
            imageList: [], // 图片列表
            locationInfo: '', // 位置信息
            description: '', // 描述信息
            createTime: '', // 拍照时间
            communityList: ['社区A', '社区B', '社区C', '社区D'], // 社区列表
            communityIndex: 0, // 选中的社区索引
            loading: false, // 加载状态
            mapApiKey: 'X4SBZ-ZKYCL-G5QP7-MRBOJ-ZYRQK-UGFV4', // 腾讯地图API Key
            mapSecretKey: 'MXmC6JWEX0ODwRBfcxK9SzCuqRAKK57I' // 腾讯地图SecretKey
        }
    },
    onLoad() {
        // 初始化时间
        this.createTime = this.formatDate(new Date());
    },
    methods: {
        // 格式化日期
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hour = String(date.getHours()).padStart(2, '0');
            const minute = String(date.getMinutes()).padStart(2, '0');
            return `${year}-${month}-${day} ${hour}:${minute}`;
        },

        // 选择图片
        chooseImage() {
            uni.chooseImage({
                count: 1, // 最多可以选择的图片张数
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['camera'], // 从相机选图
                success: (res) => {
                    this.imageList = res.tempFilePaths;
                    this.uploadImage(res.tempFilePaths[0]);
                },
                fail: (err) => {
                    uni.showToast({
                        title: '拍照失败',
                        icon: 'none'
                    });
                }
            });
        },

        // 预览图片
        previewImage(index) {
            uni.previewImage({
                current: this.imageList[index],
                urls: this.imageList
            });
        },

        // 上传图片到服务器
        uploadImage(filePath) {
            this.loading = true;
            uni.uploadFile({
                url: 'https://your-api.com/upload', // 服务器接口地址
                filePath: filePath,
                name: 'file',
                success: (res) => {
                    const data = JSON.parse(res.data);
                    if (data.code === 0) {
                        uni.showToast({
                            title: '上传成功',
                            icon: 'success'
                        });
                        // 保存服务器返回的图片URL
                        this.imageList = [data.data.url];
                    } else {
                        uni.showToast({
                            title: '上传失败',
                            icon: 'none'
                        });
                    }
                },
                fail: (err) => {
                    uni.showToast({
                        title: '上传失败',
                        icon: 'none'
                    });
                },
                complete: () => {
                    this.loading = false;
                }
            });
        },

        // 获取位置信息
        getLocation() {
            this.loading = true;
            uni.getLocation({
                type: 'wgs84',
                success: (res) => {
                    // 调用逆地理编码API获取地址信息
                    this.reverseGeocoder(res.latitude, res.longitude);
                },
                fail: (err) => {
                    uni.showToast({
                        title: '获取位置失败，请手动输入',
                        icon: 'none'
                    });
                    this.loading = false;
                }
            });
        },

        // 生成地图API签名
        generateMapSign(params) {
            const sortedParams = Object.keys(params)
                .filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
                .sort()
                .reduce((obj, key) => {
                    obj[key] = params[key];
                    return obj;
                }, {});
            
            const paramStr = Object.entries(sortedParams)
                .map(([key, value]) => `${key}=${value}`)
                .join('&');
            
            const signStr = `${paramStr}${this.mapSecretKey}`;
            return md5(signStr).toUpperCase();
        },

        // 逆地理编码，将经纬度转换为地址
        reverseGeocoder(latitude, longitude) {
            // 请求参数
            const params = {
                location: `${latitude},${longitude}`,
                key: this.mapApiKey,
                get_poi: 0, // 是否返回周边POI
                timestamp: Math.floor(Date.now() / 1000), // 秒级时间戳
                nonce: Math.random().toString(36).substr(2, 10) // 随机字符串
            };
            
            // 生成签名
            params.sig = this.generateMapSign(params);
            
            console.log('请求参数:', params); // 调试用
            
            // 发送请求
            uni.request({
                url: 'https://apis.map.qq.com/ws/geocoder/v1/',
                method: 'GET',
                data: params,
                success: (res) => {
                    console.log('地图API响应:', res.data);
                    if (res.data.status === 0) {
                        this.locationInfo = res.data.result.address;
                    } else {
                        uni.showToast({
                            title: `位置解析失败: ${res.data.message}`,
                            icon: 'none'
                        });
                    }
                },
                fail: (err) => {
                    console.error('地图API请求失败:', err);
                    uni.showToast({
                        title: '解析位置失败',
                        icon: 'none'
                    });
                },
                complete: () => {
                    this.loading = false;
                }
            });
        },

        // 社区选择变化
        onCommunityChange(e) {
            this.communityIndex = e.detail.value;
        },

        // 提交表单
        submitForm() {
            // 表单验证
            if (!this.imageList.length) {
                uni.showToast({
                    title: '请拍照上传',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.locationInfo) {
                uni.showToast({
                    title: '请获取位置信息',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.description.trim()) {
                uni.showToast({
                    title: '请填写详细描述',
                    icon: 'none'
                });
                return;
            }

            // 构建提交数据
            const formData = {
                imageUrl: this.imageList[0],
                location: this.locationInfo,
                description: this.description,
                createTime: this.createTime,
                community: this.communityList[this.communityIndex]
            };

            this.loading = true;
            // 提交数据到服务器
            uni.request({
                url: 'https://your-api.com/submit',
                method: 'POST',
                data: formData,
                success: (res) => {
                    if (res.data.code === 0) {
                        uni.showToast({
                            title: '提交成功',
                            icon: 'success'
                        });
                        // 提交成功后返回上一页或跳转到成功页面
                        setTimeout(() => {
                            uni.navigateBack();
                        }, 1500);
                    } else {
                        uni.showToast({
                            title: res.data.message || '提交失败',
                            icon: 'none'
                        });
                    }
                },
                fail: (err) => {
                    uni.showToast({
                        title: '网络错误，请稍后再试',
                        icon: 'none'
                    });
                },
                complete: () => {
                    this.loading = false;
                }
            });
        }
    }
}
</script>

<style lang="scss" scoped>
.container {
    padding: 30rpx;
    background-color: #f5f5f5;
}

.title-section {
    text-align: center;
    padding: 30rpx 0;
    .title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
    }
}

.form-item {
    background-color: #fff;
    border-radius: 12rpx;
    margin-bottom: 24rpx;
    padding: 24rpx 30rpx;
    .label {
        display: block;
        font-size: 28rpx;
        color: #333;
        margin-bottom: 16rpx;
    }
    .form-value {
        font-size: 28rpx;
        color: #666;
    }
}

.upload-area {
    display: flex;
    flex-wrap: wrap;
    .upload-btn {
        width: 160rpx;
        height: 160rpx;
        border: 2rpx dashed #ddd;
        border-radius: 12rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .image {
            width: 48rpx;
            height: 48rpx;
            margin-bottom: 10rpx;
        }
        text {
            font-size: 24rpx;
            color: #999;
        }
    }
    .image-preview {
        margin-left: 20rpx;
        image {
            width: 160rpx;
            height: 160rpx;
            border-radius: 12rpx;
            margin-right: 20rpx;
        }
    }
}

.location-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10rpx 0;
    text {
        font-size: 28rpx;
        color: #666;
    }
    image {
        width: 24rpx;
        height: 24rpx;
    }
}

textarea {
    width: 100%;
    min-height: 160rpx;
    font-size: 28rpx;
    color: #666;
}

.picker {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10rpx 0;
    text {
        font-size: 28rpx;
        color: #666;
    }
    image {
        width: 24rpx;
        height: 24rpx;
    }
}

.submit-section {
    padding: 30rpx 0;
    .submit-btn {
        width: 100%;
        height: 88rpx;
        line-height: 88rpx;
        background-color: #007AFF;
        color: #fff;
        font-size: 32rpx;
        border-radius: 44rpx;
        border: none;
    }
}
</style>    